"""
扫货账号管理页面
"""
from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget,
                           QTableWidgetItem, QPushButton, QLineEdit, QLabel,
                           QHeaderView, QFrame, QCheckBox, QMessageBox, QFileDialog)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QColor
from com.db.scan_account_manager import ScanAccountManager
from com.db.models import ScanAccount
from gui.styles.table_style import apply_default_table_style, set_columns_stretch
from gui.styles.pagination_style import PaginationWidget
from gui.widgets.add_scan_account_dialog import AddScanAccountDialog
from gui.widgets.scan_frequency_config_dialog import ScanFrequencyConfigDialog
from biz.account_checker import AccountChecker, AccountType
import logging
import json
from datetime import datetime

# 配置日志
logger = logging.getLogger(__name__)

class ScanAccountPage(QWidget):
    """扫货账号管理页面"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.account_manager = ScanAccountManager()
        self.account_checker = AccountChecker()
        self.setup_ui()
        self.load_accounts()  # 从数据库加载账号数据
        self.setup_connections()  # 设置信号连接
    
    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)  # 移除边距，使表格占满整个空间
        layout.setSpacing(0)  # 减少间距
        
        # 搜索区域
        search_frame = QFrame()
        search_frame.setStyleSheet("""
            QFrame {
                background-color: white;
                border: none;
                border-bottom: 1px solid #ebeef5;
            }
        """)
        search_layout = QHBoxLayout(search_frame)
        search_layout.setContentsMargins(15, 10, 15, 10)
        
        # 左侧搜索区域
        left_widget = QWidget()
        left_layout = QHBoxLayout(left_widget)
        left_layout.setContentsMargins(0, 0, 0, 0)
        left_layout.setSpacing(10)
        
        # 搜索输入框
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入账号名称搜索")
        self.search_input.setStyleSheet("""
            QLineEdit {
                padding: 5px 10px;
                border: 1px solid #dcdfe6;
                border-radius: 2px;
                font-size: 12px;
                color: #606266;
                min-width: 200px;
            }
            QLineEdit:focus {
                border-color: #409eff;
            }
        """)
        
        # 搜索按钮
        search_btn = QPushButton("搜索")
        search_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #66b1ff;
            }
        """)
        
        # 重置按钮
        reset_btn = QPushButton("重置")
        reset_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: white;
                color: #606266;
                border: 1px solid #dcdfe6;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                color: #409eff;
                border-color: #c6e2ff;
                background-color: #ecf5ff;
            }
        """)
        
        # 导出按钮
        export_btn = QPushButton("导出")
        export_btn.setStyleSheet(reset_btn.styleSheet())
        
        left_layout.addWidget(self.search_input)
        left_layout.addWidget(search_btn)
        left_layout.addWidget(reset_btn)
        left_layout.addWidget(export_btn)
        
        # 右侧按钮区域
        right_widget = QWidget()
        right_layout = QHBoxLayout(right_widget)
        right_layout.setContentsMargins(0, 0, 0, 0)
        right_layout.setSpacing(10)
        
        # 扫货时间频率配置按钮
        freq_config_btn = QPushButton("扫货时间频率配置")
        freq_config_btn.setObjectName("freqConfigBtn")
        freq_config_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #66b1ff;
            }
        """)
        
        # 刷新按钮
        refresh_btn = QPushButton("刷新")
        refresh_btn.setObjectName("refreshBtn")
        refresh_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #67c23a;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #85ce61;
            }
        """)
        
        # 导入按钮
        import_btn = QPushButton("导入")
        import_btn.setObjectName("importBtn")
        import_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #66b1ff;
            }
        """)
        
        # 添加按钮
        add_btn = QPushButton("添加/更新账号")
        add_btn.setObjectName("addBtn")
        add_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #67c23a;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #85ce61;
            }
        """)
        
        right_layout.addWidget(freq_config_btn)
        right_layout.addWidget(refresh_btn)
        right_layout.addWidget(import_btn)
        right_layout.addWidget(add_btn)
        
        # 将左右两侧添加到主布局
        search_layout.addWidget(left_widget)
        search_layout.addStretch()
        search_layout.addWidget(right_widget)
        
        # 表格
        self.table = QTableWidget()
        apply_default_table_style(self.table)
        
        # 设置表格列
        headers = ["uu用户id", "名称", "uutoken", "设备id", "uk", "扫货最大间隔时间", "创建时间", "更新时间", "状态", "操作"]
        self.table.setColumnCount(len(headers))
        self.table.setHorizontalHeaderLabels(headers)
        
        # 设置表格列宽
        set_columns_stretch(self.table)
        
        # 分页控件
        self.pagination = PaginationWidget()
        self.pagination.prev_btn.clicked.connect(self.on_prev_page)
        self.pagination.next_btn.clicked.connect(self.on_next_page)
        self.pagination.page_size_spin.valueChanged.connect(self.on_page_size_changed)
        
        # 添加到主布局
        layout.addWidget(search_frame)
        layout.addWidget(self.table)
        layout.addWidget(self.pagination)
    
    def load_accounts(self, keyword=None):
        """从数据库加载账号数据"""
        # 计算总数
        total_count = len(self.account_manager.get_accounts())
        
        # 获取当前页数据
        page = self.pagination.page
        page_size = self.pagination.page_size
        offset = (page - 1) * page_size
        
        # 获取分页数据
        accounts = self.account_manager.get_accounts(keyword, limit=page_size, offset=offset)
        
        # 更新分页状态
        self.pagination.update_state(page, total_count)
        
        # 更新表格
        self.table.setRowCount(len(accounts))
        
        for row, account in enumerate(accounts):
            # uu用户id
            uu_user_id_item = QTableWidgetItem(str(account.get('uu_user_id', '')))
            uu_user_id_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 0, uu_user_id_item)
            
            # 名称
            name_item = QTableWidgetItem(account['name'])
            name_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 1, name_item)
            
            # uutoken
            token_item = QTableWidgetItem(account.get('uu_token', ''))
            token_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 2, token_item)
            
            # 设备ID
            device_id_item = QTableWidgetItem(account.get('device_id', ''))
            device_id_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 3, device_id_item)
            
            # uk
            uk_item = QTableWidgetItem(account.get('uk', ''))
            uk_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 4, uk_item)
            
            # 扫货最大间隔时间
            max_interval_item = QTableWidgetItem(str(account.get('max_interval', '')))
            max_interval_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 5, max_interval_item)
            
            # 创建时间
            create_at = account.get('create_at', '')
            create_at_str = self.format_timestamp(create_at)
            create_at_item = QTableWidgetItem(create_at_str)
            create_at_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 6, create_at_item)
            
            # 更新时间
            update_at = account.get('update_at', '')
            update_at_str = self.format_timestamp(update_at)
            update_at_item = QTableWidgetItem(update_at_str)
            update_at_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 7, update_at_item)
            
            # 状态
            status = "启用" if account.get('status', 0) == 1 else "禁用"
            status_item = QTableWidgetItem(status)
            status_item.setForeground(QColor("#67c23a") if status == "启用" else QColor("#f56c6c"))
            status_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 8, status_item)
            
            # 操作按钮
            action_widget = QWidget()
            action_layout = QHBoxLayout(action_widget)
            action_layout.setContentsMargins(4, 4, 4, 4)
            action_layout.setSpacing(8)
            
            button_styles = {
                "删除": ("#f56c6c", "#fef0f0"),
                "检测": ("#409eff", "#ecf5ff"),
                "启用": ("#67c23a", "#f0f9eb"),
                "停用": ("#e6a23c", "#fdf6ec")
            }
            
            # 添加启用/停用按钮
            status_btn_text = "停用" if account.get('status', 0) == 1 else "启用"
            status_btn = QPushButton(status_btn_text)
            status_btn.setFixedSize(45, 25)
            color, bg_color = button_styles[status_btn_text]
            status_btn.setStyleSheet(f"""
                QPushButton {{
                    padding: 0px;
                    background-color: {bg_color};
                    border: none;
                    border-radius: 2px;
                    font-size: 12px;
                    color: {color};
                }}
                QPushButton:hover {{
                    background-color: {color};
                    color: white;
                }}
            """)
            status_btn.clicked.connect(lambda checked, a=account: self.toggle_account_status(a))
            action_layout.addWidget(status_btn)
            
            for action in ["删除", "检测"]:
                btn = QPushButton(action)
                btn.setFixedSize(45, 25)
                color, bg_color = button_styles[action]
                btn.setStyleSheet(f"""
                    QPushButton {{
                        padding: 0px;
                        background-color: {bg_color};
                        border: none;
                        border-radius: 2px;
                        font-size: 12px;
                        color: {color};
                    }}
                    QPushButton:hover {{
                        background-color: {color};
                        color: white;
                    }}
                """)
                if action == "删除":
                    btn.clicked.connect(lambda checked, a=row: self.delete_account(a))
                elif action == "检测":
                    btn.clicked.connect(lambda checked, a=row: self.check_account(a))
                action_layout.addWidget(btn)
            
            action_layout.addStretch()
            self.table.setCellWidget(row, 9, action_widget)
            
            # 设置行高
            self.table.setRowHeight(row, 45)
        
        # 更新分页按钮状态
        self.pagination.prev_btn.setEnabled(self.pagination.page > 1)
        self.pagination.next_btn.setEnabled(self.pagination.page < (total_count + page_size - 1) // page_size)
    
    def format_timestamp(self, timestamp):
        """将时间戳转换为年-月-日 时:分:秒格式
        
        Args:
            timestamp: 时间戳（毫秒）
            
        Returns:
            str: 格式化后的时间字符串
        """
        if not timestamp:
            return ""
        
        # 转换为秒
        try:
            # 确保timestamp是整数
            timestamp = int(timestamp)
            # 如果是毫秒时间戳，转换为秒
            if timestamp > 9999999999:
                timestamp = timestamp / 1000
            
            # 转换为datetime对象并格式化
            dt = datetime.fromtimestamp(timestamp)
            return dt.strftime("%Y-%m-%d %H:%M:%S")
        except Exception as e:
            logger.error(f"时间戳转换失败: {e}")
            return str(timestamp)

    def on_prev_page(self):
        """上一页"""
        if self.pagination.page > 1:
            self.pagination.page -= 1
            self.load_accounts()
    
    def on_next_page(self):
        """下一页"""
        total_pages = (self.pagination.total_count + self.pagination.page_size - 1) // self.pagination.page_size
        if self.pagination.page < total_pages:
            self.pagination.page += 1
            self.load_accounts()
    
    def on_page_size_changed(self, value):
        """页面大小改变"""
        self.pagination.page_size = value
        self.pagination.page = 1  # 重置到第一页
        self.load_accounts()
    
    def on_search(self):
        """搜索处理"""
        keyword = self.search_input.text().strip()
        self.pagination.page = 1  # 重置到第一页
        self.load_accounts(keyword if keyword else None)
    
    def on_reset(self):
        """重置处理"""
        self.search_input.clear()
        self.pagination.page = 1
        self.load_accounts()
    
    def on_edit_account(self, account):
        """编辑账号"""
        # TODO: 实现编辑功能
        print(f"编辑账号: {account['id']}")
    
    def delete_account(self, row):
        """删除账号
        
        Args:
            row: 表格行号
        """
        try:
            # 从ScanAccountManager获取账号信息
            accounts = self.account_manager.get_accounts()
            if not accounts:
                raise ValueError("未找到账号信息")
                
            account = accounts[row]
            account_id = account['id']
            account_name = account['name']
            
            # 确认删除
            reply = QMessageBox.question(
                self,
                "确认删除",
                f"确定要删除账号 {account_name} 吗？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No
            )
            
            if reply == QMessageBox.StandardButton.Yes:
                # 执行删除
                if self.account_manager.delete_account(account_id):
                    self.table.removeRow(row)
                    QMessageBox.information(self, "提示", "删除成功")
                else:
                    QMessageBox.warning(self, "错误", "删除失败")
                    
        except Exception as e:
            logger.error(f"删除账号时发生错误: {str(e)}")
            QMessageBox.warning(self, "错误", f"删除账号时发生错误: {str(e)}")
    
    def check_account(self, row):
        """检测账号
        
        Args:
            row: 表格行号
        """
        try:
            # 获取当前页面的所有账号
            page = self.pagination.page
            page_size = self.pagination.page_size
            offset = (page - 1) * page_size
            accounts = self.account_manager.get_accounts(
                keyword=self.search_input.text().strip(),
                limit=page_size,
                offset=offset
            )
            
            # 根据行号获取对应的账号
            if not accounts or row >= len(accounts):
                raise ValueError("未找到账号信息")
                
            account = accounts[row]
            account_id = account['id']
            
            # 执行检测
            success, message, _ = self.account_checker.check_account(
                account_id=account_id,
                account_type=AccountType.SCAN  # 这里是扫货账号页面
            )
            
            # 刷新账号列表，获取最新状态
            self.load_accounts()
            
            # 显示提示信息
            if success:
                QMessageBox.information(self, "检测结果", message)
            else:
                QMessageBox.warning(self, "检测结果", message)
                
        except Exception as e:
            logger.error(f"检测账号时发生错误: {str(e)}")
            QMessageBox.warning(self, "错误", f"检测账号时发生错误: {str(e)}")
    
    def toggle_account_status(self, account):
        """切换账号状态（启用/停用）
        
        Args:
            account: 账号数据
        """
        account_id = account.get('id')
        current_status = account.get('status', 0)
        new_status = 0 if current_status == 1 else 1
        status_text = "启用" if new_status == 1 else "停用"
        
        # 确认对话框
        reply = QMessageBox.question(
            self,
            "确认操作",
            f"确定要{status_text}账号 {account.get('name', '')} 吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            # 更新账号状态
            success = self.account_manager.update_account_status(account_id, status=new_status)
            
            if success:
                QMessageBox.information(self, "操作成功", f"账号已{status_text}")
                # 刷新账号列表
                self.load_accounts()
            else:
                QMessageBox.warning(self, "操作失败", f"账号{status_text}失败")
    
    def setup_connections(self):
        """设置信号连接"""
        # 找到添加按钮并连接点击事件
        add_btn = self.findChild(QPushButton, "addBtn")
        if add_btn:
            add_btn.clicked.connect(self.show_add_dialog)
            
        # 找到导入按钮并连接点击事件
        import_btn = self.findChild(QPushButton, "importBtn")
        if import_btn:
            import_btn.clicked.connect(self.import_accounts)
        
        # 找到扫货时间频率配置按钮并连接点击事件
        freq_config_btn = self.findChild(QPushButton, "freqConfigBtn")
        if freq_config_btn:
            freq_config_btn.clicked.connect(self.show_frequency_config_dialog)
            
        # 找到刷新按钮并连接点击事件
        refresh_btn = self.findChild(QPushButton, "refreshBtn")
        if refresh_btn:
            refresh_btn.clicked.connect(self.refresh_accounts)
        
        # 搜索按钮
        search_btn = self.findChild(QPushButton, "搜索")
        if search_btn:
            search_btn.clicked.connect(self.on_search)
        
        # 重置按钮
        reset_btn = self.findChild(QPushButton, "重置")
        if reset_btn:
            reset_btn.clicked.connect(self.on_reset)
            
    def import_accounts(self):
        """导入账号"""
        # 打开文件选择对话框
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择账号数据文件",
            "",
            "JSON Files (*.json);;All Files (*)"
        )
        
        if not file_path:
            return
            
        try:
            # 读取JSON文件
            with open(file_path, 'r', encoding='utf-8') as f:
                accounts = json.load(f)
                
            if not isinstance(accounts, list):
                QMessageBox.warning(self, "错误", "无效的账号数据格式")
                return
                
            success_count = 0
            update_count = 0
            error_count = 0
            
            # 导入每个账号
            for account in accounts:
                try:
                    # 检查必要字段
                    required_fields = ['name', 'uu_token', 'device_id', 'uu_user_id']
                    if not all(field in account for field in required_fields):
                        error_count += 1
                        continue
                        
                    # 设置时间戳
                    account['create_at'] = account.get('create_at', datetime.utcnow().isoformat())
                    account['update_at'] = int(datetime.now().timestamp() * 1000)
                    
                    # 处理tags字段，确保是字符串格式
                    if 'tags' in account:
                        if isinstance(account['tags'], list):
                            account['tags'] = json.dumps(account['tags'])
                        elif account['tags'] is None:
                            account['tags'] = '[]'
                    
                    # 检查是否存在相同uu_user_id的账号
                    session, query = self.account_manager.db.query_with_session(ScanAccount)
                    try:
                        uu_user_id = account.get('uu_user_id')
                        existing_account = query.filter(ScanAccount.uu_user_id == uu_user_id).first()
                        is_update = existing_account is not None
                    finally:
                        session.close()
                    
                    # 保存到数据库
                    if self.account_manager.add_account(account):
                        if is_update:
                            update_count += 1
                        else:
                            success_count += 1
                    else:
                        error_count += 1
                        
                except Exception as e:
                    logger.error(f"导入账号失败: {str(e)}")
                    error_count += 1
                    
            # 显示导入结果
            message = f"导入完成\n\n新增: {success_count}\n更新: {update_count}\n失败: {error_count}"
            QMessageBox.information(self, "导入结果", message)
            
            # 重新加载数据
            self.load_accounts()
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导入失败: {str(e)}")

    def show_add_dialog(self):
        """显示添加账号对话框"""
        dialog = AddScanAccountDialog(self)
        if dialog.exec():
            # 获取表单数据
            account_data = dialog.get_form_data()
            if account_data:
                # 检查是否已存在相同uu_user_id的账号
                session, query = self.account_manager.db.query_with_session(ScanAccount)
                try:
                    uu_user_id = account_data.get('uu_user_id')
                    existing_account = query.filter(ScanAccount.uu_user_id == uu_user_id).first()
                    is_update = existing_account is not None
                finally:
                    session.close()
                
                # 记录从 account_data 获取的 UK 值
                uk_value = account_data.get('uk', '')
                logger.debug(f"保存到数据库前的 UK 值: {uk_value}")
                logger.debug(f"保存到数据库前的 account_data: {account_data}")
                
                # 保存到数据库
                if self.account_manager.add_account(account_data):
                    message = "更新账号成功" if is_update else "添加账号成功"
                    QMessageBox.information(self, "提示", message)
                    # 重新加载数据
                    self.load_accounts()
                else:
                    QMessageBox.warning(self, "错误", "操作失败，请检查账号信息是否完整")
            else:
                QMessageBox.warning(self, "错误", "请先完成登录验证")

    def show_frequency_config_dialog(self):
        """显示扫货时间频率配置对话框"""
        dialog = ScanFrequencyConfigDialog(self)
        dialog.exec()
    
    def refresh_accounts(self):
        """刷新账号列表"""
        try:
            self.load_accounts()
            logger.info("账号列表刷新成功")
        except Exception as e:
            logger.error(f"刷新账号列表失败: {str(e)}")
            QMessageBox.warning(self, "提示", "刷新账号列表失败")
